<template>
  <el-form
    ref="ruleFormRef"
    :model="ruleForm"
    :rules="rules"
    label-width="0"
    class="demo-ruleForm"
    status-icon
  >
    <el-form-item prop="username">
      <el-input v-model.trim="ruleForm.username" placeholder="请输入手机号" />
    </el-form-item>
    <el-form-item prop="imageCode">
      <el-input
        v-model.trim="ruleForm.imageCode"
        type="text"
        placeholder="图片验证码"
        class="code"
      >
        <template #append>
          <img
            :src="imgSrc"
            alt=""
            class="w-[90px] h-[30px] cursor-pointer"
            @click="getCode"
          />
        </template>
      </el-input>
    </el-form-item>
    <el-form-item prop="smsCode">
      <el-input
        v-model.trim="ruleForm.smsCode"
        type="text"
        placeholder="短信验证码"
      >
        <template #append>
          <span
            v-if="time === 0"
            class="cursor-pointer text-red-500"
            @click="debounceSendSms"
            >发送验证码</span
          >
          <span v-else>请{{ time }}秒后重试</span>
        </template>
      </el-input>
    </el-form-item>
    <el-form-item prop="password">
      <el-input
        v-model.trim="ruleForm.password"
        placeholder="新密码6至16位，包含大小写字母、数字"
      />
    </el-form-item>
    <el-form-item>
      <el-button type="primary" class="w-full" @click="resetSubmit(ruleFormRef)"
        >重置密码</el-button
      >
    </el-form-item>
  </el-form>
</template>

<script setup lang="ts">
import { ElMessage, FormInstance, FormRules } from "element-plus";
import { onMounted, ref } from "vue";
import { useRouter } from "vue-router";
import { reactive } from "vue";
import { checkMobile } from "../utils/rule";
import { getValidateCode, sendPasswordCode } from "@/api/user";
import { debounce } from "@pureadmin/utils";
defineOptions({
  name: "resetPassword"
});
const router = useRouter();

onMounted(() => {
  getCode();
});
// 获取图形验证码
const imgSrc = ref();
let key = "";
const getCode = async () => {
  const res = await getValidateCode();
  if (res.code === 0) {
    key = res.data.key;
    imgSrc.value = res.data.imageCode;
  }
};
// 发送验证码
const time = ref(0);
let timer: null | number = null;
const sendSms = () => {
  ruleFormRef.value.validateField(["imageCode", "username"], async valid => {
    if (valid) {
      const { imageCode, username } = ruleForm.value;
      const res = await sendPasswordCode({
        imageCode,
        mobile: username,
        key
      });
      if (res.code === 0) {
        ElMessage.success("短信发送成功!请查收");
        time.value = 60;
        timer = window.setInterval(() => {
          time.value--;
          if (time.value === 0) {
            timer && clearInterval(timer);
            time.value = 60;
          }
        }, 1000);
      }
    }
  });
};
const debounceSendSms = debounce(sendSms, 1000, true);
interface ResetForm {
  username: string;
  imageCode: string;
  password: string;
  smsCode: string;
}
const ruleForm = ref<ResetForm>({
  username: "",
  password: "",
  smsCode: "",
  imageCode: ""
});
const ruleFormRef = ref<FormInstance>();
const rules = reactive<FormRules<typeof ruleForm>>({
  username: [
    {
      validator: checkMobile,
      trigger: "blur"
    }
  ],
  smsCode: {
    required: true,
    message: "请输入短信验证码",
    trigger: "blur"
  },
  imageCode: {
    required: true,
    message: "请输入图形验证码",
    trigger: "blur"
  }
});
const loading = ref(false);
const resetSubmit = async (formEl: FormInstance | undefined) => {
  if (!formEl) return;
  await formEl.validateField(["username", "smsCode"], (valid, fields) => {
    if (valid) {
      loading.value = true;
      ElMessage.success("重置成功");
      router.replace({
        path: "/login"
      });
    } else {
      return fields;
    }
  });
};
</script>
<style lang="scss" scoped>
.el-input {
  height: 36px;
}

:deep(.code .el-input-group__append) {
  background-color: #fff;
}
</style>
